<?php
if(PERMISSION != "P")
{
	redirectPage("index.php?module=logout");
	exit();
}

$clsEncypt = new clsEncrypt();
$clsEncypt->pubkey = "CrossWordGame";

if(PERMISSION == "P")
{
	$play_count = $db_mysql->get_field_value("SELECT COUNT(*) FROM games Where user_id = '$user_id_login'");
//	var_dump($play_count);
	if(isset($_SESSION['user_token']))
	{
	}
	else
	{
		$current_datetime = date("Y-m-d H:i:s");
		$hash_time = $clsEncypt->encrypt($current_datetime);

		// commit token to session
		$_SESSION['user_token'] = $hash_time;
	}
}

if(isset($_POST['user_token']))
{
	//We check if the token of the page and session match!
	if($_POST['user_token'] == $_SESSION['user_token'] && isset($_SESSION['crossword_grid']) && isset($_SESSION['crossword_legend']) && isset($_SESSION['crossword_word_count']) && $play_count < 2)
	{
		$start_time = $clsEncypt->decrypt($db_mysql->db_input($_POST['user_token']));
		
		$crossword_id = $db_mysql->db_input(setVar("crossword_id",""));
        $user_id = $user_id_login;     
		$user_word_grid = setVar("user_word_grid",""); 
		$user_word_correct = calculate_word_correct($user_word_grid, $_SESSION['crossword_grid']);
		
		$user_word_grid = $db_mysql->db_input_json($user_word_grid);
		
		$end_time = date("Y-m-d H:i:s");
		
		$activate = 1;
		
		$fields_values = array(
            "user_id"=>$user_id,
            "crossword_lang"=>$user_lang_login,
            "crossword_grid"=>$db_mysql->db_input_json($_SESSION['crossword_grid']),
            "crossword_legend"=>$db_mysql->db_input_json($_SESSION['crossword_legend']),
            "crossword_word_count"=>$db_mysql->db_input($_SESSION['crossword_word_count']),
            "user_word_grid"=>$user_word_grid,
            "user_word_correct"=>$user_word_correct,
            "start_time"=>$start_time,
            "end_time"=>$end_time,
            "activate" => $activate,
			'ip_address' => $db_mysql->db_input(getIPAddress()),
			'client_info' => $db_mysql->db_input($_SERVER['HTTP_USER_AGENT']),
			'from_device' => $db_mysql->db_input(DEVICE_INFO)
        );
		$fields_values['date_created'] = date("Y-m-d H:i:s");
		
		$game_id = "";
		
		insert_db("games", $fields_values, "game_id", $game_id, false);
		
		if(!$db_mysql->is_errors())
		{
			if($db_type == "mysql")
			{
				$sql = "UPDATE games SET user_time = TIME_TO_SEC(TIMEDIFF(end_time, start_time)) WHERE game_id = '$game_id'";
			}
			else
			{
				$sql = "UPDATE games SET user_time = DATEDIFF(SECOND, start_time, end_time) WHERE game_id = '$game_id'";
			}
			$db_mysql->query($sql);
			unset($_SESSION['user_token']);
			unset($_SESSION['crossword_grid']);
			unset($_SESSION['crossword_legend']);
			unset($_SESSION['crossword_word_count']);
			redirectPage("index.php?module=thank_you");
		}
		else
		{
			$message = 'DB error!';
		}
		
	}
	else 
	{
		echo 'Your request has expired, please go back and resubmit!';
		unset($_SESSION['user_token']);
		exit();
	}
}
if(file_exists($cw_data_url))
{
	$raw_data = file_get_contents($cw_data_url);
	if($raw_data)
	{
		$data = unserialize($clsEncypt->decrypt($raw_data));
		$_SESSION['crossword_grid'] = $data[$user_lang_login]["grid"];
		$_SESSION['crossword_legend'] = $data[$user_lang_login]["legend"];
		$_SESSION['crossword_word_count'] = $data[$user_lang_login]["word_count"];
	}
	else
	{
		exit();
	}
}
else
{
	exit();
}

if($data["active_cw"] == 0)
{
	if($user_lang_login == "en")
		echo "Crossword Game is not available now. Please come back later";
	else
		echo "Trò chơi ô chữ hiện nay chưa sẵn sàng. Vui lòng quay lại sau.";
	
	exit();
}

$arr_legend = json_decode($data[$user_lang_login]["legend"], true);
$arr_grid = json_decode($data[$user_lang_login]["grid"], true);

delete_char_grid($arr_grid);

$json_arr_grid = json_encode($arr_grid);

?>
<?
//echo "<pre>";
//print_r($arr_grid);
//echo "</pre>";
?>
<?php include('includes/header.php'); ?>
<script src="js/jquery.stopwatch.js" type="text/javascript"></script>
<div id="content">
	<div id="stage-2" style="display:block">
	<?
	if(isset($play_count) && $play_count < 2)
	{
	?>
		<script>
			$(document).ready(function(){
				$.APP.startTimer('sw');
			});
		</script>
		<div id="stopwatch" style="width: 100%;text-align: center">
			<span id="sw_h">00</span> :
			<span id="sw_m">00</span> :
			<span id="sw_s">00</span>
		</div>
		<div class="clear"></div>
	<form name="frmView" id="frmView" action="" method="post">
		<input type="hidden" name="user_token" value="<?php echo  isset($_SESSION['user_token']) ? $_SESSION['user_token'] : "";  ?>" />
		<textarea id="user_word_grid" rows="50" cols="50" name="user_word_grid" class='hide'></textarea>
	</form>	
	<div class="button" id="finish-up">
		<a href="javascript:;" onclick="sendAnswer();"><?php if($user_lang_login == 'vn') echo 'Gửi câu trả lời'; else echo'Submit';?></a>
		<?php
			if($user_lang_login == 'vn'){ ?>
				Bạn đã chơi <strong><?=$play_count?></strong> lần!
		<?php } else { ?>
				You played <strong><?=$play_count?></strong> time(s)!
		<?php }?>
		
    </div>
	<?php	
	}
	else
	{
	?>
	<div class="button" id="finish-up">
		<?php
			if($user_lang_login == 'vn'){ ?>
				Bạn đã chơi <strong><?=$play_count?></strong> lần!
		<?php } else { ?>
				You played <strong><?=$play_count?></strong> times!
		<?php }?>
		
    </div>
	<?php
	}
	?>
		<h2 style="display:none;" id="title"><?=$data[$user_lang_login]["title"]?> - <?=  strtoupper($user_lang_login)?></h2>    
    <div id="crossword">
		<table class='crossword'>
			<?php
			for($i = 0; $i < count($arr_grid); $i++)
			{
				$row = $arr_grid[$i];
			?>
			<tr>
			<?php
			for($j = 0; $j < count($row); $j++)
			{
				$cell = $row[$j];

				if(is_array($cell))//has char
				{
					$is_start_of_word = 0;
					$index = 0;
					$position = "";
					$char = $cell["char"];
					
					$across = $cell["across"];
					if(is_array($across))
					{
						$is_start_of_word = $across["is_start_of_word"] ? 1 : 0;
						if($is_start_of_word == 1)
						{
							$position = get_position_by_index($arr_legend, $across["index"], "across");
						}
					}
					
					$down = $cell["down"];
					if(is_array($down) && $is_start_of_word == 0)
					{
						$is_start_of_word = $down["is_start_of_word"];
						if($is_start_of_word == 1)
						{
							$position = get_position_by_index($arr_legend, $down["index"], "down");
						}
					}
					$style = $position ? "background-image:url('https://crosswordlabs.com/media/img/numbers/".($position).".png');" : "";
					?>
				<td class='' id='cell-<?=$i?>-<?=$j?>' style="<?=$style?>">
					<input type='text' size='1' maxlength='1' class='hidden-field' />
				</td>
					<?
				}
				else//no char
				{
				?>
				<td class='no-border ' id='cell-<?=$i?>-<?=$j?>'>
					&nbsp;
				</td>
				<?
				}
			}
			?>
			</tr>
			<?	
			}
			?>
		</table>
    </div>

	<div id="clues">
		<div id="clues-inner">    
            <div id="across-box">
                <h5>
                	<?php
						if($user_lang_login == 'vn'){ ?>
							Ngang
					<?php } else { ?>
							Across
					<?php }?>
                	
                </h5>
                <ol id="across">
                    <?php
					foreach($arr_legend["across"] as $word)
					{
						$position = $word["position"];
						$index = $word["index"];
						$clue = $word["clue"];
					?>
					<li id="clue-<?=$index?>"><strong><?=$position?>.</strong> <?=$clue?></li>
					<?php
					}
					?>
                </ol>
            </div>
            <div id="down-box">        
                <h5>
                	<?php
						if($user_lang_login == 'vn'){ ?>
							Dọc
					<?php } else { ?>
							Down
					<?php }?>
                	
                	
                </h5>
                <ol id="down">
                    <?php
					foreach($arr_legend["down"] as $word)
					{
						$position = $word["position"];
						$index = $word["index"];
						$clue = $word["clue"];
					?>
					<li id="clue-<?=$index?>"><strong><?=$position?>.</strong> <?=$clue?></li>
					<?php
					}
					?>
                </ol>
            </div>
        </div>
    </div>
    <div class="clear"></div>
</div>
<script type="text/javascript">
var grid = 	<?=$json_arr_grid?>;
var index_to_row_column = [];
for(var r = 0; r < grid.length; r++){
	for(var c = 0; c < grid[r].length; c++){
		var cell = grid[r][c];
		if(cell == null) continue;
		if(cell['across'] && cell['across']['is_start_of_word'])
			index_to_row_column[cell['across']['index']] = {"row" : r, "col" : c};
		if(cell['down'] && cell['down']['is_start_of_word'])
			index_to_row_column[cell['down']['index']] = {"row" : r, "col" : c};			
	}
}
</script>
<script type="text/javascript" src="js/view.js"></script>
</div>

